<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/15
 * Time: 10:30
 */

namespace app\home\controller;


use app\common\model\AmountLog;
use app\common\model\Config;
use app\common\model\Level;
use app\common\model\MessageTemplate;
use app\common\model\NoticeMessage;
use app\common\model\ServiceOrder;
use app\common\model\ServiceTopLog;
use app\common\model\UserCommission;
use app\Request;

class Service
{
    public function addService(Request $request){
        $param = $request->param();
        $data= [
            'title' => $param['title'],
            'pid_tab' => $param['pid_tab'],
            'son_tab' => $param['son_tab'],
            'describe' => $param['describe'],
            'sex' => $param['sex'],
            'address' =>  $param['address'],
            'service_time' => $param['service_time'],
            'content_img' => $param['content_img'],
            'work_time' => $param['work_time'],
            'label' => $param['label'],
            'cover_img' => $param['cover_img'],
            'uid' => $request->userInfo['id'],
            'price' => $param['price'],
            'create_time' => time(),
            'vice_title' => $param['vice_title'],
            'longitude' => $param['longitude'],
            'dimension' => $param['dimension'],
        ];
        if (isset($param['describe_speech']) && !empty($param['describe_speech'])){
            $data['describe_speech']  = $param['describe_speech'];
        }
        if (isset($param['game_level']) && !empty($param['game_level'])){
            $data['game_level']  = $param['game_level'];
        }
        $serviceModel = new \app\common\model\Service();
        if ($request->userInfo['level_id'] > 1) {
            $service_number = Config::getConfigValue('level_service_number');
        } else {
            $service_number = Config::getConfigValue('service_number');
        }
        if ($service_number  >0  ){
            $todayServiceCount = $serviceModel->where('create_time'  ,strtotime(date('Y-m-d 00:00:00')))
                ->where('uid','=', $request->userInfo['id'])
                ->count();
            if ($service_number <= $todayServiceCount ){
                return error('今日发布数量已达上限');
            }
        }
        $isAuditing = Config::getConfigValue('service_status');
        if ($isAuditing == 1){
            $data['status']  = '1';
        }else{
            $data['status']  = '2';
        }
        $longitude = number_format(doubleval($data['longitude']), 6);
        $latitude = number_format(doubleval($data['dimension']), 6);
        $gps = $latitude . ',' . $longitude;
        $params = array(
            'location' => $gps,
            'key'=> Config::getConfigValue('tencent_map_key'),
        );
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
        $url = $url . '?' . http_build_query($params, '', '&');
        $mapResult  = json_decode(curlGet($url));
        if ($mapResult->status == 0 ){
            /* return error('百度地图数据获取有误')*/
            $data['province_name'] = $mapResult->result->address_component->province;
            $data['city_name'] = $mapResult->result->address_component->city;
            $data['area_name'] = $mapResult->result->address_component->district;
            $data['address'] = $mapResult->result->address;
        };
        $serviceModel->insert($data);
        if ($isAuditing != 1){
            $messageModel = new MessageTemplate();
            $xcxMessage[0]['data'] = [
                'thing1' => ['value' => '服务'],
                'thing2' => ['value' => $data['title']],
                'phrase3' => ['value' =>'通过'],
                'time5' => ['value' => date('Y-m-d H:i:s')],
            ];
            $xcxMessage[0]['uid'] =$request->userInfo['id'];
            $xcxMessage[0]['title'] ='release';
            $messageModel->sendMessage(3,$xcxMessage);
            $gzhMessage[0]['data'] = [
                'thing10' => ['value' =>'服务'],
                'thing28' => ['value' => $request->userInfo['nickname'] ],
                'thing9' => ['value' =>$data['title']],
                'thing2' => ['value' => '通过'],
            ];
            $gzhMessage[0]['uid'] =$request->userInfo['id'];
            $gzhMessage[0]['title'] ='release';
            $messageModel->sendMessage(1,$gzhMessage);
        }
        return success('添加成功');
    }

    public function editService(Request $request){
        $param = $request->param();
        $data= [
            'title' => $param['title'],
            'pid_tab' => $param['pid_tab'],
            'son_tab' => $param['son_tab'],
            'describe' => $param['describe'],
            'describe_speech' => $param['describe_speech'],
            'sex' => $param['sex'],
            'address' =>  $param['address'],
            'service_time' => $param['service_time'],
            'content_img' => $param['content_img'],
            'work_time' => $param['work_time'],
            'label' => $param['label'],
            'cover_img' => $param['cover_img'],
            'uid' => $request->userInfo['id'],
            'price' => $param['price'],
            'create_time' => time(),
            'vice_title' => $param['vice_title'],
            'longitude' => $param['longitude'],
            'dimension' => $param['dimension'],
        ];
        if (isset($param['game_level']) && !empty($param['game_level'])){
            $data['game_level']  = $param['game_level'];
        }
        $serviceOrderModel = new \app\common\model\ServiceOrder();

        $serviceOrderInfo = $serviceOrderModel->where(['id' => $param['id']])->find();
        if ($serviceOrderInfo){
            return error('已有用户下单,不能编辑');
        }
        $serviceModel = new \app\common\model\Service();
        $isAuditing = Config::getConfigValue('service_status');
        if ($isAuditing == 1){
            $data['status']  = '1';
        }else{
            $data['status']  = '2';
        }
        $longitude = number_format(doubleval($data['longitude']), 6);
        $latitude = number_format(doubleval($data['dimension']), 6);
        $gps = $latitude . ',' . $longitude;

        $params = array(
            'location' => $gps,
            'key'=> Config::getConfigValue('tencent_map_key'),
        );
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
        $url = $url . '?' . http_build_query($params, '', '&');
        $mapResult  = json_decode(curlGet($url));
        if ($mapResult->status == 0 ){
            /* return error('百度地图数据获取有误')*/
            $data['province_name'] = $mapResult->result->address_component->province;
            $data['city_name'] = $mapResult->result->address_component->city;
            $data['area_name'] = $mapResult->result->address_component->district;
            $data['address'] = $mapResult->result->address;
        };
        $serviceModel->where(['id' => $param['id']])->update($data);

        return success('添加成功');
    }
    public function serviceList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        $where = [];
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['status']) && !empty($param['status']) ) {
            $where[] = ['s.status', '=', $param['status']];
        }
        if (isset($param['is_oneself_uid']) && !empty($param['is_oneself_uid'])) {
            $where[] = ['s.uid','=',$param['is_oneself_uid']];
        }else{
            $where[] = ['s.status', '=', 2];
        }
        if (isset($param['uid']) && $param['uid']) {
            $where[] = ['s.uid', '=',$param['uid']];
            $where[] = ['s.status', '=', 2];
        }
        if (isset($param['son_tab']) && !empty($param['son_tab'])){
            $where[] = ['s.son_tab','=',$param['son_tab']];
        }
        if (isset($param['title']) && !empty($param['title'])){
            $where[] = ['s.title','like','%'.$param['title'].'%'];
        }
        if (isset($param['dimension']) && !empty($param['dimension']) &&
            isset($param['longitude']) && !empty($param['longitude'])){
            $dimension = $param['dimension'];
            $longitude = $param['longitude'];
        }else{
            $dimension =  Config::getConfigValue('dimension') ;
            $longitude =  Config::getConfigValue('longitude') ;
        }
        if (empty($dimension)){
            $dimension = '39.54';
        }
        if (empty($longitude)){
            $longitude = '116.23';
        }

        $sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$dimension}
         * PI() / 180 - s.dimension * PI() / 180) / 2), 2) + COS({$dimension} * PI() / 180)
          * COS(s.dimension * PI() / 180) * POW(SIN(({$longitude} * PI() / 180 - s.longitude * PI() / 180) / 2), 2))) 
          * 1000) AS distance";
        if (isset($param['service_sort_rule']) && $param['service_sort_rule'] == 1){
            $orderField = 'distance';
            $orderType = 'asc';
        }else{
            $orderField = 's.create_time';
            $orderType = 'desc';
        }
        $serviceModel = new \app\common\model\Service();
        $list = $serviceModel
            ->alias('s')
            ->leftJoin('tab_class tc', 's.son_tab = tc.id')
            ->leftJoin('user u', 's.uid = u.id')
            ->where($where)
            ->field('s.*,u.nickname,u.avatar,tc.name,tc.icon,tc.type_css,tc.label_icon,'.$sql)
            ->order('s.is_top','desc')
            ->order($orderField,$orderType)
            ->limit($start,$limit)->select()->toArray();
        $count = $serviceModel->alias('s')
            ->leftJoin('tab_class tc', 's.son_tab = tc.id')
            ->leftJoin('user u', 's.uid = u.id')
            ->where($where)
            ->count();
        foreach ($list as $key => $value){
            if ($value['top_expire_time'] > 0){
                $list[$key]['top_expire_time'] = date('Y-m-d H:i', $value['top_expire_time']);
            }
            $list[$key]['distance_kilometer']  =  haversineDistance($dimension,$longitude,$value['dimension'],$value['longitude']);

        }
        return success('服务列表',['list' =>$list,'count'=>$count ]);
    }
    public function placeServiceOrder(Request $request){
        $param = $request->param();
        $serviceModel = new \app\common\model\Service();
        $serviceInfo = $serviceModel->where(['id' =>$param['id'] ])->find();
        if ($serviceInfo['uid'] == $request->userInfo['id']){
            return error('此服务为您自己发布');
        }
        if ($serviceInfo['status']  !=  2){
            return error('此服务已下架');
        }
        $discountAmount = $serviceInfo['price'];
        $service_level_discount = 0;
        if ($request->userInfo['level_id'] > 1){
            $service_level_discount  = Config::getConfigValue('service_level_discount');
            if ($service_level_discount >0){
                $discountAmount = bcdiv(bcmul($serviceInfo['price'],$service_level_discount,2),100,2);
            }
        }
        if ($discountAmount  > $request->userInfo['balance']){
            return error('余额不足请充值',[],'1001');
        }
        $data = [
            'service_id' => $param['id'],
            'uid' => $request->userInfo['id'],
            'service_uid' =>$serviceInfo['uid'],
            'status' => 1,
            'create_time' => time(),
            'price' =>$discountAmount  ,
            'order_sn' =>getOrderNo('s_'),
            'original_price' => $serviceInfo['price'],
            'discount' =>$service_level_discount ,
        ];
        $serviceOrderModel = new \app\common\model\ServiceOrder();
       // $serviceInfo = $serviceOrderModel->where(['service_id'=>$param['id'],'uid',$request->userInfo['id']])->find();
        $userModel = new \app\common\model\User();
        try{
            $serviceOrderModel->startTrans();
            $serviceOrderModel->insert($data);
            $id  = $serviceOrderModel->getLastInsID();
            if ($serviceInfo['price'] > 0 ){
                $amountModel = new AmountLog();
                $amountData  = [
                    'uid' => $request->userInfo['id'],
                    'amount' => $serviceInfo['price'],
                    'amount_type' => 1,
                    'amount_direction' => 2,
                    'create_time' => time(),
                    'correlation_id' => $id,
                    'operation_source' => 6,
                    'ratio' =>$service_level_discount,
                    'original_price' =>  $serviceInfo['price'],
                ];
                $amountModel->insert($amountData);
            }
         /*   $noticeMessageModel = new  NoticeMessage();
            $noticeMessageModel->insert([
                // 'content' =>  $param['content'],
                'uid'=> $request->userInfo['id'],
                'receive_uid' => $serviceInfo['uid'],
                'type' => 12,
                'service_id' =>  $serviceInfo['id'],
                'create_time' => time(),
                'is_read' => 0
            ]);*/
            $userModel->where(['id' => $request->userInfo['id']])->dec('balance',$discountAmount);
            $serviceOrderModel->commit();
            $messageModel = new MessageTemplate();
            $xcxMessage[0]['data'] = [
                'thing1' => ['value' => '服务'],
                'thing2' => ['value' => $serviceInfo['title']],
                'phrase3' => ['value' =>'下单'],
                'time5' => ['value' => date('Y-m-d H:i:s')],
            ];
            $xcxMessage[0]['uid'] = $serviceInfo['uid'];

            $xcxMessage[0]['title'] ='release';
            $gzhMessage[0]['data'] = [
                'thing10' => ['value' =>'服务'],
                'thing28' => ['value' => $request->userInfo['nickname'] ],
                'thing9' => ['value' =>$serviceInfo['title']],
                'thing2' => ['value' => '下单'],
            ];
            $gzhMessage[0]['uid'] =$serviceInfo['uid'];
            $gzhMessage[0]['title'] ='release';

            if ($serviceInfo['price'] > 0){
                $xcxMessage[1]['data'] =  [
                    'amount2' => ['value' => $serviceInfo['price']],
                    'thing8' => ['value' => '服务下单'],
                    'thing5' => ['value' => $serviceInfo['title']],
                    'time4' =>  ['value' => date('Y-m-d H:i')],
                ];
                $xcxMessage[1]['uid'] = $request->userInfo['id'];
                $xcxMessage[1]['title'] ='consumption';
                $gzhMessage[1]['data'] = [
                    'thing2' => ['value' =>'服务下单'],
                    'thing37' => ['value' =>  $serviceInfo['title']],
                    'amount3' => ['value' =>$serviceInfo['price']],
                    'time6' => ['value' => date('Y-m-d H:i')],
                ];
                $gzhMessage[1]['uid'] = $request->userInfo['id'];
                $gzhMessage[1]['title'] ='consumption';
            }
            $messageModel->sendMessage(3,$xcxMessage);
            $messageModel->sendMessage(1,$gzhMessage);
            $messageModel-> sendAliMessage($serviceInfo['uid'], 'release', ['name' =>'服务'. $serviceInfo['title'],'desc'=>'新订单']);
        }catch (Exception $exception){
            $serviceOrderModel->rollback();
            return error($exception->getMessage());
        }
        return success('下单成功');
    }
    /**
     * 我下单的服务订单
     */
    public function  serviceUserOrder(Request $request){
        $param = $request->param();
        $serviceOrderModel = new ServiceOrder();
        $limit = 10;
        $start = 0;
        $where[] = ['so.uid' ,'=', $request->userInfo['id']];
        if (isset($param['title']) && !empty($param['title']) ) {
            $where[] = ['s.title', '=', $param['title']];
        }
        if (isset($param['order_sn']) && !empty($param['order_sn']) ) {
            $where[] = ['so.order_sn', '=', $param['order_sn']];
        }
        if (isset($param['id']) && !empty($param['id']) ) {
            $where[] = ['s.id', '=', $param['id']];
        }
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['status']) && !empty($param['status']) ) {
            $where[] = ['s.status', '=', $param['status']];
        }
        if (isset($param['order_status']) && !empty($param['order_status']) ) {
            $where[] = ['so.status', '=', $param['order_status']];
        }
        $list = $serviceOrderModel->alias('so')
            ->leftJoin('service s', 'so.service_id = s.id')
            ->leftJoin('user u', 'so.service_uid = u.id')
            ->where($where)
            ->field('s.*,u.nickname,u.avatar,so.id as service_order_id,so.status as order_status,so.create_time,so.is_comment,so.remark as service_order_remark')
            ->order('so.create_time','desc')
            ->limit($start,$limit)
            ->select()->toArray();
        $count = $serviceOrderModel->alias('so')
            ->where($where)
            ->leftJoin('service s', 'so.service_id = s.id')
            ->leftJoin('user u', 'so.service_uid = u.id')
            ->field('s.*,.u.nickname,u.avatar')
            ->count();
        return success('我下单的服务',['list' => $list,'count' => $count]);
    }
    /**
     * @param 我发布服务的服务订单
     */
    public function myServiceOrder(Request $request){
        $param = $request->param();
        $serviceOrderModel = new ServiceOrder();
        $limit = 10;
        $start = 0;
        $where[] = ['so.service_uid' ,'=', $request->userInfo['id']];
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['status']) && !empty($param['status']) ) {
            $where[] = ['s.status', '=', $param['status']];
        }
        if (isset($param['order_status']) && !empty($param['order_status']) ) {
            $where[] = ['so.status', '=', $param['order_status']];
        }
        if (isset($param['nickname']) && !empty($param['nickname']) ) {
            $where[] = ['u.nickname', 'like', '%'.$param['nickname'].'%'];
        }
        if (isset($param['title']) && !empty($param['title']) ) {
            $where[] = ['s.title', 'like', '%'.$param['title'].'%'];
        }
        if (isset($param['order_sn']) && !empty($param['order_sn']) ) {
            $where[] = ['so.order_sn','like', '%'.$param['order_sn'].'%'];
        }
        if (isset($param['id']) && !empty($param['id']) ) {
            $where[] = ['so.service_id', '=', $param['id']];
        }
        $list = $serviceOrderModel->alias('so')
            ->leftJoin('service s', 'so.service_id = s.id')
            ->leftJoin('tab_class tc', 's.son_tab = tc.id')
            ->leftJoin('user u', 'so.uid = u.id')
            ->where($where)
            ->field('s.*,u.nickname,u.avatar,
            u.id as service_order_uid,
            so.id as service_order_id ,
             so.order_sn,
             so.status as order_status,so.create_time,
            so.remark as service_order_remark,
            tc.name,tc.icon,tc.type_css,tc.label_icon')
            ->order('so.create_time','desc')
            ->limit($start,$limit)
            ->select()->toArray();
        $count = $serviceOrderModel->alias('so')
            ->leftJoin('service s', 'so.service_id = s.id')
            ->leftJoin('tab_class tc', 's.son_tab = tc.id')
            ->leftJoin('user u', 'so.uid = u.id')
            ->where($where)
            ->count();
        return success('我下单的服务',['list' => $list,'count' => $count]);
    }

    /**
     * @param Request $request
     * 服务用户接单
     */
    public function takingOrder(Request $request){
        $param = $request->param();
        $serviceOrderModel = new \app\common\model\ServiceOrder();
        $serviceOrderModel->where(['id' => $param['id']])
            ->update(['status' => 2, 'update_time' => time(),]);
        return success('成功');
    }
    public function refuseServiceOrder(Request $request){
        $param = $request->param();
        $serviceOrderModel = new \app\common\model\ServiceOrder();
        $serviceOrderInfo = $serviceOrderModel->where(['id' => $param['id']])->find();
        if ($serviceOrderInfo['status'] != 1 ){
            return error('订单状态有误');
        }
        $serviceOrderModel->where(['id' => $param['id']])
            ->update(['status' => 5, 'update_time' => time(),'remark' => $param['remark']]);
        $userModel = new \app\common\model\User();
        $userModel->where(['id' => $serviceOrderInfo['uid']])
            ->inc('balance',$serviceOrderInfo['price'])->update();
        $amountModel = new AmountLog();
        $amountData  = [
            'uid' => $serviceOrderInfo['uid'],
            'amount' => $serviceOrderInfo['price'],
            'amount_type' => 1,
            'amount_direction' => 1,
            'create_time' => time(),
            'correlation_id' => $param['id'],
            'operation_source' => 7
        ];
        $amountModel->insert($amountData);
     /*   $noticeMessageModel = new  NoticeMessage();
        $noticeMessageModel->insert([
            // 'content' =>  $param['content'],
            'uid'=> $request->userInfo['id'],
            'receive_uid' => $serviceOrderInfo['uid'],
            'type' => 15,
            'service_id' =>  $serviceOrderInfo['service_id'],
            'create_time' => time(),
            'is_read' => 0
        ]);*/
       /* $amountModel = new AmountLog();
        $amountData  = [
            'uid' => $serviceOrderInfo['uid'],
            'amount' => $serviceOrderInfo['price'],
            'amount_type' => 1,
            'amount_direction' => 1,
            'create_time' => time(),
            'correlation_id' => $param['id'],
            'operation_source' => 7
        ];
        $amountModel->insert($amountData);*/
        $serviceModel = new \app\common\model\Service();
        $serviceInfo = $serviceModel->where(['id' => $serviceOrderInfo['service_id']])->find();
        $messageModel = new MessageTemplate();
        $xcxMessage[]['data'] =  [
            'thing1' => ['value' => '服务订单'],
            'thing2' => ['value' => $serviceInfo['title']],
            'phrase3' => ['value' =>'拒绝'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];
        $xcxMessage[0]['uid'] = $serviceOrderInfo['uid'];
        $xcxMessage[0]['title'] ='release';
        $messageModel->sendMessage(3,$xcxMessage);
        $gzhMessage[0]['data'] = [
            'thing10' => ['value' =>'社群'],
            'thing28' => ['value' => $request->userInfo['nickname'] ],
            'thing9' => ['value' =>$serviceInfo['title']],
            'thing2' => ['value' => '通过'],
        ];
        $gzhMessage[0]['uid'] =$serviceOrderInfo['uid'];
        $gzhMessage[0]['title'] ='release';
        $messageModel->sendMessage(1,$gzhMessage);
        $messageModel-> sendAliMessage($serviceOrderInfo['uid'], 'release', ['name' =>'服务'. $serviceInfo['title'],'desc'=>'拒绝订单']);

        return success('操作成功');
    }
    public function completeServiceOrder(Request $request)
    {
        $param = $request->param();
        $serviceOrderModel = new \app\common\model\ServiceOrder();
        $serviceOrderInfo = $serviceOrderModel->where(['id' => $param['id']])->find();
        if ($serviceOrderInfo['service_uid']  != $request->userInfo['id']){
            return error('完成自己的订单');
        }
        $data  =  [
            'complete_img' => $param['complete_img'],
            'status' => 3,
            'update_time' => time(),
            'remark' => $param['remark']
        ];
        $serviceOrderModel->where(['id' => $param['id']])->update($data);
      /*  $noticeMessageModel = new  NoticeMessage();
        $noticeMessageModel->insert([
            // 'content' =>  $param['content'],
            'uid'=> $request->userInfo['id'],
            'receive_uid' => $serviceOrderInfo['uid'],
            'type' => 13,
            'service_id' =>  $serviceOrderInfo['service_id'],
            'create_time' => time(),
            'is_read' => 0
        ]);*/
        $serviceModel = new \app\common\model\Service();
        $serviceInfo = $serviceModel->where(['id' => $serviceOrderInfo['service_id']])->find();
        $messageModel = new MessageTemplate();
        $xcxMessage[]['data'] =  [
            'thing1' => ['value' => '服务订单'],
            'thing2' => ['value' => $serviceInfo['title']],
            'phrase3' => ['value' =>'完成'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];
        $xcxMessage[0]['uid'] = $serviceOrderInfo['uid'];
        $xcxMessage[0]['title'] ='release';
        $messageModel->sendMessage(3,$xcxMessage);

        $gzhMessage[0]['data'] = [
            'thing10' => ['value' =>'服务订单'],
            'thing28' => ['value' => $request->userInfo['nickname'] ],
            'thing9' => ['value' =>$serviceInfo['title']],
            'thing2' => ['value' => '完成'],
        ];
        $gzhMessage[0]['uid'] =$serviceOrderInfo['uid'];
        $gzhMessage[0]['title'] ='release';
        $messageModel->sendMessage(1,$gzhMessage);
        $messageModel-> sendAliMessage($serviceOrderInfo['uid'], 'release', ['name' =>'服务'. $serviceInfo['title'],'desc'=>'完成订单']);

        return success('操作成功');
    }
    public function commentService(Request $request){
        $param = $request->param();
        $serviceOrderModel = new \app\common\model\ServiceOrder();
        $serviceModel = new \app\common\model\Service();
        $serviceOrderInfo = $serviceOrderModel->where(['id' => $param['id']])->find();
        if ($serviceOrderInfo['uid']  != $request->userInfo['id']){
            return error('请评论自己的订单');
        }
        if ($serviceOrderInfo['is_comment']  == 1){
            return error('请勿重复评论');
        }
        $data  =  [
            'technology_score' => $param['technology_score'],
            'service_score' => $param['service_score'],
            'voice_score' => $param['voice_score'],
            'evaluate' => $param['evaluate'],
            'evaluate_img' => $param['evaluate_img'],
            'update_time' => time(),
            'is_comment' => 1,

        ];
        $serviceModel->where(['id' => $serviceOrderInfo['service_id']])
            ->inc('technology_score_total',$param['technology_score'])
            ->inc('service_score_total',$param['service_score'])
            ->inc('voice_score_total',$param['voice_score'])
            ->inc('comment_number')
            ->update();
        $serviceOrderModel->where(['id' => $param['id']])->update($data);
        return success('操作成功');
    }
    public function settlementService(Request $request){
        $param = $request->param();
        $serviceOrderModel = new \app\common\model\ServiceOrder();
        $serviceOrderInfo = $serviceOrderModel->where(['id' => $param['id']])->find();
        if ($serviceOrderInfo['status'] != 3){
            return error('订单状态有误,请刷新页面');
        }
        if ($serviceOrderInfo['uid']  != $request->userInfo['id']){
            return error('请结算自己的订单');
        }
        $serviceOrderModel->where(['id' => $param['id']])->update(['status' => 4,'update_time'=> time()]);
      /*  if ($serviceOrderInfo['price'] > 0 ) {
            $amountModel = new AmountLog();
            $amountData = [
                'uid' => $serviceOrderInfo['service_uid'],
                'amount' => $serviceOrderInfo['price'],
                'amount_type' => 2,
                'amount_direction' => 1,
                'create_time' => time(),
                'correlation_id' => $param['id'],
                'operation_source' => 8
            ];
            $amountModel->insert($amountData);
        }*/

        $userModel = new \app\common\model\User();
        $fees = Config::getConfigValue('service_fees');
        $platformAmount = bcdiv(bcmul((string)$serviceOrderInfo['price'], (string)$fees, 2), '100', 2);
        $amount = bcsub((string)$serviceOrderInfo['price'], (string)$platformAmount, 2);
        $recharge_ratio  = Config::getConfigValue('recharge_ratio');
        $userModel->where(['id' => $serviceOrderInfo['service_uid']])
            ->inc('total_income', (float)$amount)
            ->inc('surplus_income', (float)$amount)
            ->inc('service_income', (float)$amount)
            ->inc('service_number')
            ->update();
        $amountLog = [
            'uid' =>  $serviceOrderInfo['service_uid'],
            'amount' => $amount,
            'amount_type' => 2,
            'operation_source' => 10,
            'amount_direction' => 1,
            'create_time' => time(),
            'correlation_id' => $param['id'],
            'ratio' => $fees,
            'handling_fees_amount' => bcdiv($platformAmount,$recharge_ratio,2),
            'handling_fees' => $platformAmount,
            'original_price' =>$serviceOrderInfo['price']
        ];
        $amountModel = new  AmountLog();
        $amountModel->insert($amountLog);

 /*       $userCommissionModel = new UserCommission();
        $userCommissionModel->addUserCommission($serviceOrderInfo['service_uid'],$serviceOrderInfo['price'],2,$serviceOrderInfo['id']);
        $userModel = new \app\common\model\User();
        $userModel->where(['id' => $serviceOrderInfo['service_uid']])->inc('service_number')->update();*/
     /*   $noticeMessageModel = new  NoticeMessage();
        $noticeMessageModel->insert([
            // 'content' =>  $param['content'],
            'uid'=> $request->userInfo['id'],
            'receive_uid' => $serviceOrderInfo['uid'],
            'type' => 14,
            'service_id' =>  $serviceOrderInfo['service_id'],
            'create_time' => time(),
            'is_read' => 0
        ]);*/
        $serviceModel = new \app\common\model\Service();
        $serviceModel->where(['id' => $serviceOrderInfo['service_uid']])->inc('order_number')->update();
        $serviceInfo = $serviceModel->where(['id' => $serviceOrderInfo['service_id']])->find();
        $messageModel = new MessageTemplate();
        $xcxMessage[]['data'] =  [
            'thing1' => ['value' => '服务订单'],
            'thing2' => ['value' => $serviceInfo['title']],
            'phrase3' => ['value' =>'结算'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];
        $xcxMessage[0]['uid'] = $serviceInfo['uid'];
        $xcxMessage[0]['title'] ='release';
        $messageModel->sendMessage(3,$xcxMessage);

        $gzhMessage[0]['data'] = [
            'thing10' => ['value' =>'服务订单'],
            'thing28' => ['value' => $request->userInfo['nickname'] ],
            'thing9' => ['value' =>$serviceInfo['title']],
            'thing2' => ['value' => '结算'],
        ];
        $gzhMessage[0]['uid'] =$serviceInfo['uid'];
        $gzhMessage[0]['title'] ='release';
        $messageModel->sendMessage(1,$gzhMessage);
        $messageModel-> sendAliMessage($serviceInfo['uid'], 'release', ['name' =>'服务'. $serviceInfo['title'],'desc'=>'已结算']);


        return success('操作成功');
    }
    public function upServiceStatus(Request $request){
        $param = $request->param();
        $serviceModel = new \app\common\model\Service();
        if ($param['status'] ==3 ){
            $serviceOrderModel = new \app\common\model\ServiceOrder();
            $count  = $serviceOrderModel->where(['service_id' => $param['id']])
                ->where('status','in',[1,2])->count();
            if ($count> 0){
                return error('服务存在未处理的订单');
            }
        }
        $serviceModel->where(['id' => $param['id'] ])->update(['status' => $param['status']]);
        return success('操作成功');
    }
    public function serviceInfo(Request $request){
        $param = $request->param();
        $serviceModel = new \app\common\model\Service();
        $serviceInfo = $serviceModel->where(['id' => $param['id']])->find();
        return success('服务详情',$serviceInfo);
    }
    public function serviceCommentList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['is_comment','=',1];
        if (isset($param['id']) && !empty($param['id'])) {
            $where[] = ['service_id','=',$param['id']];
        }
        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['service_uid','=',$param['uid']];
        }
        $serviceOrderModel = new \app\common\model\ServiceOrder();
        $list = $serviceOrderModel
            ->alias('s')
            ->leftJoin('user u','s.uid = u.id')
            ->where($where)
            ->field('s.*,u.nickname,u.avatar')
            ->order('s.create_time','desc')
            ->limit($start,$limit)
            ->select()->toArray();
        $count = $serviceOrderModel
            ->alias('s')
            ->leftJoin('user u','s.uid = u.id')
            ->where($where)
            ->count();
        return success('服务评价',['list' => $list,'count' => $count]);
    }
    public function serviceTop(Request $request){
        $param = $request->param();
        if ($param['day']<= 0){
            return error('请设置正确的天数');
        }
        $serviceTopNumber =  Config::getConfigValue('service_top_number');
        $serviceModel =  new \app\common\model\Service();
        $count = $serviceModel->where(['is_top' => 1,'status' => 2])->count();
        if ($count >= $serviceTopNumber ){
            return error('置顶数量已经最大');
        }
        $serviceInfo = $serviceModel->where(['id' => $param['id']])->find();
        if ($serviceInfo['uid'] != $request->userInfo['id']){
            return error('请操作自己的服务');
        }

        if ($serviceInfo['top_expire_time'] > time()){
            $effective_time_start =  $serviceInfo['top_expire_time'];
        }else{
            $effective_time_start = time();
        }

        $service_top_price =  Config::getConfigValue('service_top_price');
        $service_top_level_ratio  = 0;
        $original_price = bcmul($service_top_price,$param['day'],2);
        $total_price = $original_price;
        if ($request->userInfo['level_id'] > 1) {
            $service_top_level_ratio  = Config::getConfigValue('service_top_level_ratio');
            if ($service_top_level_ratio > 0) {
                $total_price = bcdiv(bcmul($total_price, $service_top_level_ratio, 2), 100, 2);
            }
        }
        if ($request->userInfo['balance'] < $total_price) {
            return error('余额不足');
        }
        $data = [
            'service_id' =>$param['id'],
            'uid' => $request->userInfo['id'],
            'unit_price' => $service_top_price,
            'total_price' =>  $total_price,
            'day' => $param['day'],
            'ratio' => $service_top_level_ratio,
            'effective_time' => $effective_time_start +  bcmul($param['day'],86400,2),
            'original_price' => $original_price,
        ];
        $daziTopLogModel = new ServiceTopLog();
        $daziTopLogModel->insert($data);
        $daziTopLogId = $daziTopLogModel->getLastInsID();
        $userModel = new \app\common\model\User();
        $userModel->where(['id' => $request->userInfo['id']])->dec('balance',$data['total_price'])->update();
        $recharge_ratio = Config::getConfigValue('recharge_ratio');
        $handling_fees_amount =  bcdiv($data['total_price'],$recharge_ratio,2);
        $serviceModel->where(['id' => $param['id']])->update(['is_top' => 1,'top_expire_time' => $data['effective_time']]);
        $amountData = [
            'uid' =>   $request->userInfo['id'],
            'amount' => $data['total_price'],
            'amount_type' => 1,
            'operation_source' => 21,
            'amount_direction' => 2,
            'create_time' => time(),
            'correlation_id'  => $daziTopLogId,
            'ratio' => 1,
            'original_price' =>$original_price,
            'handling_fees' =>$data['total_price'],
            'handling_fees_amount' =>$handling_fees_amount
        ];
        $amountModel = new   AmountLog();
        $amountModel->insert($amountData);
        return success('操作成功');
    }

}






/* @copyright: ©2024 永州 微聚商网络科技有限公司
 @link: https://www.wEijuyunke.com*/